define(['config', 'text!app/module/system/materialPurchase.html', 'laypage',
    'mydialog', 'autocomplete','jqGrid', 'common', 'laydate'
], function (config, viewHTML, laypage,
    mydialog, autocomplete,jqGrid,common, laydate) {
	
	var token = (cache.go("token") === 'undefined') ? 'none' : cache.go("token");

    var grid_url = "/api/materialsPurchase";
    

    var model = avalon.define({
    	$id : "materialPurchase",
         // 查询条件,
    	purchaseSingleNo:"",
        materialPurchaseInfo:{
            id: "",
            uuid: "",
            purchaseSingleNo: "",//采购单号
            supplier: "",//供应商
            createBy: "",//创建人
            createDate: "",//创建日期
            status: "",//状态
            totalQuantity:"",//总数量
            amount:""//总金额
    	},
        query: {
            purchaseSingleNo:""
        },
        queryProduction:{
        },
         statusArr: [],
         selected: [],
         roles: [],
         init: function () {
             model.loadGrid();
             model.addEvent();
         },
         loadGrid: function () {
             function t(val, opt, row) {
            	 var html_con = '<div class="operating" data-id="' + row.id + '"><span class="fa fa-edit mrb" title="修改"><a href="index.html#!/108"/></span><span class="fa fa-trash-o mrb" title="删除"></span>' + (row.is_deleted == 1 ? '<span class="fa fa-reply mrb" title="恢复"></span>' : '') + '</div>';
            	 return html_con;
             }
           var i = Public.setGrid();

             $("#grid").jqGrid({
                 loadBeforeSend: function (jqXHR) {
                     jqXHR.setRequestHeader("X-AuthToken", token);
                 },
                 datatype: "json",
                 mtype: "POST",
                 url: grid_url+"/list",
                 postData: model.query.$model,
                 loadComplete: function (data) {},
                 loadError: function (xhr, status, error) {
                     alert(JSON.parse(xhr.responseText).msg);
                 },
                 colModel: [{
                         name: "operating",
                         label: "操作",
                         width: '5%',
                         formatter: t
                     },
                     {
                         name:"status",
                         label:"状态",
                         width:"10%",
                         formatter:function(value,options,rowData){
                             if(value === 0){
                                 return "草稿";
                             }else if(value === 10){
                                 return "已审核";
                             }else if(value === 20){
                                 return "已到货";
                             }else{
                                 return "草稿";
                             }
                         }
                     },
                     {
                         name: "purchaseSingleNo",
                         label: "采购单号",
                         width: '13%'
                     },
                     {
                         name: "supplier",
                         label: "供应商",
                         width: '10%'
                     },{
                         name: "totalQuantity",
                         label: "总数量",
                         width: '10%'
                     },
                     {
                         name: "amount",
                         label: "总金额",
                         width: '10%'
                     },
                     {
                         name: "createBy",
                         label: "创建人",
                         width: '10%'
                     },
                     {
                         name: "createDate",
                         label: "创建日期",
                         width: '10%',
                         formatter:function (value) {
                          return  Public.custDatefmter(value);
                         }
                     }
                 ],
                 cmTemplate: {
                     sortable: false,
                     title: false,
                     align: "center"
                 },
                 //分页
                 page: 1,
                 rowNum: 10,
                 rowList: [10, 20, 30],
                 height: i.h,
                 autowidth: true,
                 pager: '#page',
                 sortname: 'id',
                 viewrecords: true,
                 forceFit: false,
                 rownumbers: true,
                 multiselect: true,
                 multiboxonly: true,
                 sortorder: "desc",
                 jsonReader: {
                     root: "data.list",
                     records: "data.totalRow",
                     total: "data.totalPage",
                     repeatitems: false,
                     id: "id"
                 },
                 loadError: function () {
                     parent.Public.tips({
                         type: 1,
                         content: "加载数据异常！"
                     })
                 }
             });
         },
        reLoadGrid: function () {
            $("#grid").jqGrid("setGridParam", {
                url: grid_url+"/list",
                datatype : "json",
                mtype : "POST",
                page:1
            }).trigger("reloadGrid");
        },
         reset: function () {
             model.query.purchaseSingleNo="";
             model.queryData();
         },
         queryData: function () {
             $("#grid").jqGrid("setGridParam", {
                 url: grid_url+"/list",
                 datatype: "json",
                 mtype: 'POST',
                 postData:  model.query.$model
             }).trigger("reloadGrid");

         },
        affirm:function () {
            //到货确认
            dialog({
                title: "确认操作",
                content: "确定到货吗？ ",
                okValue: "确定",
                ok: function () {
                  var ids =  $("#grid").jqGrid('getGridParam', 'selarrrow');
                  var purchaseSingleNo=[];
               $.each(ids,function (index,el) {
                   var rowData = $('#grid').jqGrid('getRowData',el);
                   console.log(rowData.status);
                   if (rowData.status=="已审核"){
                       purchaseSingleNo.push(rowData.purchaseSingleNo);
                   }else if(rowData.status=="已到货"){
                    dialog({
                           title: "错误",
                           content: "已到货请勿重复操作!",
                           okValue: "确定",
                           ok: function() {}
                       }).showModal();
                       return;
                   }else {
                       dialog({
                           title: "错误",
                           content: "仅审核后才可以到货!",
                           okValue: "确定",
                           ok: function() {}
                       }).showModal();
                       return;
                   }

               });
                    $.ajax({
                        contentType: "application/json;charset=utf-8",
                        type:"POST",
                        url:"/api/materialsPurchase/affirm",
                        data:JSON.stringify(purchaseSingleNo),
                        success: function (data) {
                            if(data.success){
                                model.reLoadGrid();
                            }else{
                                alert("Failed: " +JSON.stringify(responseData) );
                            }
                        },
                        beforeSend: function (xhr) {
                            xhr.setRequestHeader("X-AuthToken", token);
                        },
                        error: function (responseData, textStatus, errorThrown) {
                            alert("Failed: " +JSON.stringify(responseData) );
                        }
                    });
                },
                cancelValue: "取消",
                cancel: function () {}
            }).showModal();
        },
         /**审核订单*/
         examine:function(ids){
        	 console.log('this is [ids]````````',ids);
             var rowData = $('#grid').jqGrid('getRowData',ids);
                 dialog({
                     title: "确认操作",
                     content: "确定通过审核？ ",
                     okValue: "确定",
                     ok: function () {
                         if (rowData.status == "草稿") {
                             $.ajax({
                                 type: "POST",
                                 url: "/api/materialsPurchase/changeExamine",
                                 data: {
                                     "ids": ids
                                 },
                                 success: function (data) {
                                     if(data.success){
                                         model.reLoadGrid();
                                     }else{
                                         alert("Failed: " +JSON.stringify(responseData) );
                                     }
                                 },
                                 beforeSend: function (xhr) {
                                     xhr.setRequestHeader("X-AuthToken", token);
                                 },
                                 error: function (responseData, textStatus, errorThrown) {
                                     alert("Failed: " + JSON.stringify(responseData));
                                 }
                             });
                         } else if (rowData.status == "已审核") {
                             dialog({
                                 title: "错误",
                                 content: "已到审核勿重复操作!",
                                 okValue: "确定",
                                 ok: function () {
                                 }
                             }).showModal();
                             return;
                         } else {
                             dialog({
                                 title: "错误",
                                 content: "仅草稿状态下才可以审核!",
                                 okValue: "确定",
                                 ok: function () {
                                 }
                             }).showModal();
                             return;
                         }
                     },
                     cancelValue: "取消",
                     cancel: function () {
                     }
                 }).showModal();
         },
         /**删除订单*/
         del: function (ids) {
             dialog({
                 title: "确认操作",
                 content: "确定删除？ 此操作不可恢复！",
                 okValue: "确定",
                 ok: function () {
                     $.ajax({
                         type: "POST",
                         url: "/api/materialsPurchase/delete",
                         data: {
                             "ids": ids
                         },
                         beforeSend: function (xhr) {
                             xhr.setRequestHeader("X-AuthToken", token);
                         },
                         success: function (data, status, xhr) {
                             if (data) {
                                 $('#grid').jqGrid('delRowData', ids);
                             }
                             model.queryData();
                         },
                         error: function (responseData, textStatus, errorThrown) {
                             alert("Failed: " + responseData);
                         }

                     });
                 },
                 cancelValue: "取消",
                 cancel: function () {}
             }).showModal();
         }, addEvent: function () {
        	 /**打开新的table 跳转页面*/
        	 $(".fr").on("click", "#add", function (e) {
        		 top.topManager.openPage({
        			id:"addOrder",
        			title:"新建采购明细",
        			href:'index.html#!/118?purchaseSingleNo=',
        			reload:true
        		 })
        	 });
        	 //修改订单信息
        	 $(".grid-wrap").on("click", ".fa-edit", function (e) {
                 var t = $(this).parent().data("id");
                 var rowData = $("#grid").jqGrid('getRowData',t);
                 var purchaseSingleNo = rowData.purchaseSingleNo;
                 top.topManager.openPage({
         			id:"addOrder",
         			title:"修改采购明细",
         			href:'index.html#!/118?purchaseSingleNo='+purchaseSingleNo,
         			reload:true
         		 })
             });
              //订单审核
             $("#examine").on("click",function (e) {
            	  e.preventDefault();
                  // if (Business.verifyRight("BU_DELETE")) {
                  var t = $("#grid").jqGrid("getGridParam", "selarrrow");
                  t.length ? model.examine(t.join()) : parent.Public.tips({
                      type: 2,
                      content: "请选择要审核的订单！"
                  })
             });
             // 删除
             $(".grid-wrap").on("click", ".fa-trash-o", function (t) {
                 var ei = [];
                 var e = $(this).parent().data("id");
                 ei.push(e);
                 model.del(e);
             });
             $("#search").click(function (e) {
                 e.preventDefault();
                 model.queryData();
             });
             $(".fa-refresh").click(function (e) {
                 e.preventDefault();
                 model.reset();
                 model.queryData();
             })
             $("#btn-batchDel").click(function (e) {
                 e.preventDefault();
                 // if (Business.verifyRight("BU_DELETE")) {
                 var t = $("#grid").jqGrid("getGridParam", "selarrrow");
                 t.length ? model.del(t.join()) : parent.Public.tips({
                     type: 2,
                     content: "请选择需要删除的项"
                 })
             });
         },
         initorder: function () {
	        	 model.materialPurchaseInfo={
                     id: "",
                     uuid: "",
                     purchaseSingleNo: "",//采购单号
                     supplier: "",//供应商
                     createBy: "",//创建人
                     createDate: "",//创建日期
                     status: "",//状态
                     totalQuantity:"",//总数量
                     amount:""//总金额
	        	}
            		 
             }
    })
    // 定义视图模块
    var viewmod = {
        viewtSrc: viewHTML,
        viewInit: function () {
            model.init();
        }, // 模块view加载完成后的回调方法，在刷新（F5）时可能调用两次
        viewDestroy: function () {} // 切换菜单时销毁原来的view
    };
    return viewmod;
});
